<template>
	<view class="container">
		<!-- 文本输入框 -->
		<view class="input-box">
			<textarea v-model="comment" placeholder="说点什么..." maxlength="500" class="textarea"></textarea>
			<view class="word-limit">
				{{ comment.length }}/500
			</view>
		</view>

		<!-- 图片展示区域 -->
		<view class="image-container" v-if="type === 'Picture'">
			<view v-for="(img, index) in images" :key="index" class="image-wrapper">
				<image class="image-item" :src="img" mode="aspectFit" @click="previewImage(index)"></image>
				<view class="delete-button" @click.stop="deleteImage(index)">
					<text class="delete-icon">×</text>
				</view>
			</view>
			<view v-if="images.length < 9" class="add-image" @click="addImage">
				<text>+</text>
			</view>
		</view>

		<!-- 视频展示区域 -->
		<view v-if="type === 'Video'" class="video-container">
			<view v-if="videoPath" class="video-wrapper">
				<video class="video-item" :src="videoPath" controls autoplay="false"
					></video>
			</view>
		</view>

		<!-- 选择车型 -->
		<view class="select-car" @click="goToBrand">
			<text>选择车型</text>
			<text v-if="carDetailName">{{carDetailName}}</text>
			<text v-else>请选择车辆信息</text>
		</view>

		<!-- 发布按钮 -->
		<view class="publish-button">
			<button @click="publish">发布</button>
		</view>
	</view>
</template>

<script>
	import {
		insertShareUploadPrice
	} from '@/api/car.js';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				comment: '',
				images: [],
				carId: 0,
				carDetailName: '',
				type: '',
				videoPath: ''
			}
		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				userType: 'userType',
				bgUserType: 'bgUserType'
			})
		},
		onLoad(options) {
			let that = this;
			that.carId = options.carId || 0;
			that.carDetailName = options.carDetailName || '';
			if (options.images) {
				this.images = JSON.parse(decodeURIComponent(options.images));
			}
			that.comment = options.comment || '';
			// 从路由参数中获取图片路径
			if (options.imagePaths) {
				this.images = JSON.parse(decodeURIComponent(options.imagePaths));
			}

			if (options.type) {
				this.type = options.type;
			}
			if (options.videoPath) {
				this.videoPath = decodeURIComponent(options.videoPath);
			}
		},
		methods: {
			goToBrand() {
				uni.redirectTo({
					url: `/pages/commponent/brand?images=${encodeURIComponent(JSON.stringify(this.images))}&comment=${this.comment}&type=`+this.type+`&videoPath=${encodeURIComponent(this.videoPath)}`                                 
				});
			},
			addImage() {
				uni.chooseImage({
					count: 9 - this.images.length, // 最多可以选择的图片数量
					success: (res) => {
						this.images = this.images.concat(res.tempFilePaths);
					}
				});
			},
			async publish() {
				let that = this;
				if (that.comment.trim() === '') {
					uni.showToast({
						title: '请填写评论',
						icon: 'none'
					});
					return;
				}
				if (that.type === "Picture") {
					if (that.images.length === 0) {
						uni.showToast({
							title: '请选中图片',
							icon: 'none'
						});
						return;
					}
				}
				if (that.carId === 0) {
					uni.showToast({
						title: '请选中车辆信息',
						icon: 'none'
					});
					return;
				}
				uni.showLoading({
					title: '正在发布...'
				});
				if (that.type === "Picture") {
					try {
						const uploadPromises = that.images.map((url) => that.uploadFilePromise(url));
						const results = await Promise.all(uploadPromises);
						console.log(results);
						let allImagePaths = results.map((item, index) => {
							return index === results.length - 1 ? item.value : item.value + ',';
						}).join('');
						uni.hideLoading();
						if (results.every(item => item && item.resultCode == 1)) {
							insertShareUploadPrice({
								carId: that.carId,
								userInfoId: that.uid,
								shareContent: that.comment,
								images: allImagePaths
							}).then(res => {
								if (res.resultCode == 1) {
									that.$util.Tips({
										title: '发布成功',
									}, {
										tab: 4,
										url: '/pages/community/index'
									});
								}
							})
						} else {
							that.$util.Tips({
								title: '部分图片上传失败，请重试',
							});
						}
					} catch (error) {
						console.log(error);
						uni.hideLoading();
						that.$util.Tips({
							title: '发布失败',
						});
					}
				}else if (that.type === 'Video') {
					const result = await that.uploadVideo(that.videoPath)
					if (result.resultCode) {
						that.$util.Tips({
							title: '发布成功',
						}, {
							tab: 4,
							url: '/pages/community/index'
						});
					}
				}
			},
			uploadVideo(url){
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: HTTP_REQUEST_URL + '/api/car/shareUploadVideo', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'shareVideo',
						formData: {
							carId: that.carId,
							userInfoId: that.uid,
							shareContent: that.comment,
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			uploadFilePromise(url) {
				let that = this;
				// 这里可以将文本和图片数据上传到服务器
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: HTTP_REQUEST_URL + '/api/car/shareUploadPrice',
						filePath: url,
						name: 'shareImages',
						formData: {
							carId: that.carId,
							userInfoId: that.uid,
							shareContent: that.comment,
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			previewImage(index) {
				// 调用 uni.previewImage 方法实现图片预览
				uni.previewImage({
					current: index, // 当前需要预览的图片的索引
					urls: this.images, // 预览的图片路径数组
					longPressActions: { // 长按图片时的菜单选项
						itemList: ['保存图片', '分享图片'],
						success: (data) => {
							console.log('长按图片操作：', data);
						},
						fail: (err) => {
							console.log('长按图片操作失败：', err);
						}
					}
				});
			},
			deleteImage(index) {
				// 删除指定索引的图片
				this.images.splice(index, 1);
			}
		}
	}
</script>

<style>
	/* 设置页面背景为灰色 */
	page {
		background-color: #f5f5f5;
		/* 灰色背景 */
	}

	/* 设置容器背景为白色 */
	.container {
		background-color: #fff;
		/* 白色背景 */
		padding: 20px;
		border-radius: 10px;
		/* 可选：添加圆角边框 */
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		/* 可选：添加阴影效果 */
	}

	.title {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.input-box {
		margin-bottom: 20px;
		position: relative;
		/* 为子元素定位 */
	}

	.input-box textarea {
		width: 100%;
		height: 120px;
		/* 增加文本框高度，适合多行输入 */
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 10px;
		box-sizing: border-box;
		/* 确保内边距不增加总宽度 */
		resize: none;
		/* 禁止用户调整大小 */
	}

	.word-limit {
		position: absolute;
		right: 10px;
		bottom: 10px;
		color: #999;
		font-size: 12px;
	}

	.image-container {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 20px;
	}

	.image-wrapper {
		position: relative;
		width: 70px;
		height: 70px;
		margin-right: 10px;
		margin-bottom: 10px;
	}

	.image-item {
		width: 100%;
		height: 100%;
		border-radius: 5px;
		overflow: hidden;
	}

	.delete-button {
		position: absolute;
		top: -10px;
		right: -10px;
		background-color: #ff4d4f;
		color: #fff;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 14px;
		cursor: pointer;
	}

	.add-image {
		width: 70px;
		height: 70px;
		margin-right: 10px;
		margin-bottom: 10px;
		border: 1px dashed #ccc;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.select-car {
		margin-bottom: 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.publish-button button {
		width: 100%;
		height: 40px;
		background-color: #00C7A0;
		/* 修改为指定颜色 */
		color: #fff;
		border-radius: 5px;
		display: flex;
		/* 使文字居中 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	.video-container {
		display: flex;
		margin-bottom: 20px;
	}

	.video-wrapper {
		position: relative;
		width: 145px;
		height: 145px;
		/* 根据需要调整视频高度 */
		margin-bottom: 10px;
	}

	.video-item {
		width: 100%;
		height: 100%;
		border-radius: 5px;
	}
</style>